package com.study.services;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.study.model.jdao.IinstDAO;
import com.study.model.mdao.DeportFormMapper;
import com.study.model.mdao.GoodDAO;
import com.study.model.mdao.ScheduleFormMapper;
import com.study.model.mdao.UserMDAO;
import com.study.model.pojo.Inst;
import com.study.model.pojo.Orderdetail;
import com.study.model.pojo.Orderform;
import com.study.model.vo.Cart;
import com.study.model.vo.CartBox;
import com.study.model.vo.CartBoxpur;
import com.study.model.vo.Cartpur;
import com.study.util.MaxId;

/**
 * 库存服务层
 * 
 * @author 郭星
 *
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class DeportService {
	@Autowired
	UserMDAO userMDAO;
	@Autowired
	DeportFormMapper deportFormMapper;
	@Autowired
	GoodDAO goodDAO;
	@Autowired
	ScheduleFormMapper scheduleform;
	@Autowired
	IinstDAO dao;

	/////////////////////////////////
	//////////////////////////// 库存
	/**
	 * 带条件的查询库存里的商品信息
	 * 
	 * @param selects     条件头
	 * @param selectinput 输入的客户名
	 * @param selectend   （废除）
	 * @param currentPage 页码
	 * @param pagesize    页大小
	 * @param uid         用户id
	 * @return
	 */
	public List<JSONObject> selectByPagerSql(String selects, String selectinput, String selectend, int currentPage,
			int pagesize, int uid) {

		// 查询当前员工是老板还是普通员工
		String selectByBoss = userMDAO.selectByBoss(uid);
		if (selectByBoss != null && selectByBoss.length() > 0) {
			if (selectinput.length() > 0 && !selectinput.trim().equals("")) {

				selectinput = "%" + selectinput + "%";
			}
			PageHelper.startPage(currentPage, pagesize);
			return deportFormMapper.findByQueryOrder(selects, selectinput, currentPage, pagesize, null, null);
		} else {
			// 普通员工则先获取，自己正管理的客户
			// List<Integer> selectByUserid = customerMapper.selectByUserid(uid);

			// 存储此员工管理的所有的客户Id
			List<Integer> allids = new ArrayList<>();

			if (selectinput.length() > 0 && !selectinput.trim().equals("")) {

				selectinput = "%" + selectinput + "%";
			}
			PageHelper.startPage(currentPage, pagesize);
			return deportFormMapper.findByQueryOrder(selects, selectinput, currentPage, pagesize, allids, uid);

		}

	}

	/////////////////////////////////
	//////////////////////////// 入库
	/**
	 * 带条件的查询入库表里的入库信息
	 * 
	 * @param selects     条件头
	 * @param selectinput 输入的客户名
	 * @param selectend   （废除）
	 * @param currentPage 页码
	 * @param pagesize    页大小
	 * @param uid         用户id
	 * @return
	 */
	public List<JSONObject> selectInstockesByPagerSql(String selects, String selectinput, String selectend,
			int currentPage, int pagesize, int uid) {

		// 查询当前员工是老板还是普通员工
		String selectByBoss = userMDAO.selectByBoss(uid);
		if (selectByBoss != null && selectByBoss.length() > 0) {
			if (selectinput.length() > 0 && !selectinput.trim().equals("")) {

				selectinput = "%" + selectinput + "%";
			}
			PageHelper.startPage(currentPage, pagesize);
			return deportFormMapper.findByInQueryOrder(selects, selectinput, currentPage, pagesize, null, null, null);
		} else {
			// 普通员工则先获取，自己正管理的客户
			// List<Integer> selectByUserid = customerMapper.selectByUserid(uid);

			// 存储此员工管理的所有的客户Id
			List<Integer> allids = new ArrayList<>();

			if (selectinput.length() > 0 && !selectinput.trim().equals("")) {

				selectinput = "%" + selectinput + "%";
			}
			PageHelper.startPage(currentPage, pagesize);
			return deportFormMapper.findByInQueryOrder(selects, selectinput, currentPage, pagesize, allids, uid, 1);

		}

	}

	/**
	 * 根据用户id查询仓库
	 * 
	 * @param uid
	 */
	public List<JSONObject> findDeportShelf(int uid) {
		// 查询当前员工是老板还是普通员工
		String selectByBoss = userMDAO.selectByBoss(uid);
		if (selectByBoss != null && selectByBoss.length() > 0) {
			return deportFormMapper.findShelf(null);
		} else {
			return deportFormMapper.findShelf(uid);
		}
	}

	/**
	 * 添加一个新入库单
	 * 
	 * @param titles
	 * @param deport
	 * @param havetime
	 * @param descins
	 * @return
	 */
	public int addInstock(String titles, Integer deport, Date havetime, String descins, String uid) {
		try {
			Integer fll = null;
			Integer findMaxId = deportFormMapper.findMaxId();
			System.out.println(findMaxId);
			if (findMaxId != null && findMaxId != 0) {
				fll = findMaxId;
			}
			String id = MaxId.generateNewOrderID2(fll);
			deportFormMapper.doInsert(id, titles, deport, havetime, descins, uid);
			return Integer.parseInt(id);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return 0;
		}

	}

	/**
	 * 查询入库明细并放入购物车
	 * 
	 * @param id
	 * @param cart
	 */
	public void findinstockDetail(Integer id, CartBox cart) {
		List<Cart> list = new ArrayList<>();
		List<JSONObject> findByOdidDetail = deportFormMapper.findByOdidDetail(id);
		for (JSONObject jsonObject : findByOdidDetail) {
			// System.out.println("当前详单记录："+jsonObject);
			com.study.model.vo.Good goods = goodDAO.findByGoodsIdByvo(jsonObject.getInteger("ipnum"));
			// System.out.println(goods);
			Cart carts = new Cart();
			carts.setGoods(goods);// 放入商品
			carts.setQuatity(jsonObject.getInteger("iquantity"));
			carts.setSum(jsonObject.getDoubleValue("alls"));
			carts.setDesc(jsonObject.getString("idesc"));
			// Orderdetail orderdetail = new Orderdetail();
			// Orderdetail findByoid =
			// rDetailMapper.findByoid(jsonObject.getInteger("o_id"));
			carts.setJson(jsonObject);
			list.add(carts);
		}
		cart.setMap(list);
	}

	/**
	 * 修改一条入库表的信息
	 * 
	 * @param titles
	 * @param deport
	 * @param havetime
	 * @param descins
	 * @param uid
	 * @return
	 */
	public int updateInstock(String titles, Integer deport, Date havetime, String descins, String did) {
		try {

			deportFormMapper.updateByInstockId(did, titles, deport, havetime, descins);
			return 1;
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			return 0;
		}

	}

	/**
	 * 修改对应订单、对应订单详情的数量和备注
	 * 
	 * @param quatitys
	 * @param desctext
	 * @param gidse
	 * @param idse
	 */
	public void updateQandT(Integer quatitys, String desctext, Integer gidse, Integer idse) {

		deportFormMapper.updateDetailQuatityAndDesc(quatitys, desctext, gidse, idse);
	}

	/**
	 * 查询对应入库单的信息
	 * 
	 * @param ids
	 * @return
	 */
	public JSONObject findInstock(int ids) {
		return deportFormMapper.findByInstockId(ids);
	}

	/**
	 * 更新入库详情
	 * 
	 * @param ids 入库表id
	 */
	public void deleteInStockDetail(int ids) {
		deportFormMapper.deletOrderdetails(ids);
	}

	/**
	 * 添加入库明细
	 * 
	 * @param id
	 * @param cart
	 */
	public void addOrderDetail(Integer id, CartBox cart) {
		// 查询订单概述对象
		// orderFormMapper.updateSumCount(cart.getPrice(), cart.getQuatitys(), id);
		List<Cart> map = cart.getMap();
		for (Cart cart2 : map) {
			Integer fll = null;
			Integer findMaxId = deportFormMapper.findMaxIdDetail();
			System.out.println(findMaxId);
			if (findMaxId != null && findMaxId != 0) {
				fll = findMaxId;
			}
			String detailid = MaxId.generateNewOrderID2(fll);
			deportFormMapper.insertintodetail(id, detailid, cart2.getGoods().getGooId(), cart2.getQuatity(),
					cart2.getGoods().getGooName(), cart2.getSum(), cart2.getDesc());
			// orderdetails.add(orderdetail);
		}
	}

	/**
	 * 编辑入库单为入库状态
	 * 
	 * @param id
	 */
	public void okinstock(Integer id) {
		// 添加一条入库流水
		// 查询对应采购单是否存在
		JSONObject findByInstockId = new JSONObject();
		findByInstockId = deportFormMapper.findByInstockId(id);
		if (findByInstockId != null) {
			if (findByInstockId.getInteger("schno") != null && findByInstockId.getInteger("schno") != 0) {
				scheduleform.updatestates(findByInstockId.getInteger("schno"), 3188);// 修改入库单为已入库
				scheduleform.updatedetails(findByInstockId.getInteger("schno"));// 修改詳單的入庫數量
			}
		}

		// 先修改入库单状态为已入库
		deportFormMapper.okinstock(id);
		// 查询对应入库单商品开始生成库存批次
		List<JSONObject> findByOdidDetail = deportFormMapper.findByOdidDetail(id);
		for (JSONObject jsonObject : findByOdidDetail) {
			// 生成最大编号
			Integer fll = null;
			Integer findMaxId = deportFormMapper.findMaxDepotId();
			System.out.println(findMaxId);
			if (findMaxId != null && findMaxId != 0) {
				fll = findMaxId;
			}
			String detailid = MaxId.generateNewOrderID2(fll);

			JSONObject obje = new JSONObject();
			if (jsonObject.getInteger("schno") != null && jsonObject.getInteger("schno") != 0) {
				// 查询采购时候所填写的保质期
				obje = deportFormMapper.findBypursdetail(jsonObject.getInteger("schno"),
						jsonObject.getInteger("ipnum"));
			}
			// 每个明细都要生成批次
			if (obje != null) {
				deportFormMapper.deportnum(Integer.parseInt(detailid), jsonObject.getInteger("ipnum"),
						jsonObject.getInteger("iquantity"), jsonObject.getInteger("dgsnum"),
						jsonObject.getInteger("supno"), obje.getInteger("pdtime"));
				// 修改采购单状态为已入库
			} else if (findByInstockId.getInteger("schno") != null && findByInstockId.getInteger("schno") != 0) {
				deportFormMapper.deportnum(Integer.parseInt(detailid), jsonObject.getInteger("ipnum"),
						jsonObject.getInteger("iquantity"), jsonObject.getInteger("dgsnum"),
						findByInstockId.getInteger("supno"), null);
			} else {
				deportFormMapper.deportnum(Integer.parseInt(detailid), jsonObject.getInteger("ipnum"),
						jsonObject.getInteger("iquantity"), jsonObject.getInteger("dgsnum"), null, null);
			}

			// 给每个明细添加库存批次id
			deportFormMapper.updateInstockDetailDum(jsonObject.getInteger("inum"), Integer.parseInt(detailid));

			// 插入一个流水记录
			// 生成最大编号
			Integer mid = null;
			Integer findmid = deportFormMapper.findMaxLifeId();
			System.out.println(findmid);
			if (findmid != null && findmid != 0) {
				mid = findmid;
			}
			String dd = MaxId.generateNewOrderID2(mid);
			deportFormMapper.addinputLife(Integer.parseInt(dd), 3026, jsonObject.getInteger("dgsnum"),
					jsonObject.getInteger("iquantity"), new Date(), jsonObject.getInteger("swnum"),
					jsonObject.getInteger("supno"), jsonObject.getInteger("inum"));

		}

	}

	/**
	 * 撤销对应入库单
	 * 
	 * @param ids
	 */
	public void returnScheduleform(Integer ids) {
		// 先删除对应明细
		deportFormMapper.delDetails(ids);
		// 删除对应入库单
		deportFormMapper.del(ids);
		// 查询对应采购单是否存在
		JSONObject findByInstockId = deportFormMapper.findByInstockId(ids);
		if (findByInstockId != null) {
			if (findByInstockId.getInteger("schno") != null && findByInstockId.getInteger("schno") != 0) {
				System.out.println(findByInstockId.getInteger("schno"));
				scheduleform.updatestates(findByInstockId.getInteger("schno"), 3185);// 修改入库单为已入库
				// scheduleform.updatedetails(findByInstockId.getInteger("schno"));//修改詳單的入庫數量
			}
		}

	}

	/////////////////////////////////
	//////////////////////////// 出库
	/**
	 * 带条件的查询出库表里的出库信息
	 * 
	 * @param selects     条件头
	 * @param selectinput 输入的客户名
	 * @param selectend   （废除）
	 * @param currentPage 页码
	 * @param pagesize    页大小
	 * @param uid         用户id
	 * @return
	 */
	public List<JSONObject> selectTreasiruByPagerSql(String selects, String selectinput, String selectend,
			int currentPage, int pagesize, int uid) {

		// 查询当前员工是老板还是普通员工
		String selectByBoss = userMDAO.selectByBoss(uid);
		if (selectByBoss != null && selectByBoss.length() > 0) {
			if (selectinput.length() > 0 && !selectinput.trim().equals("")) {

				selectinput = "%" + selectinput + "%";
			}
			PageHelper.startPage(currentPage, pagesize);
			return deportFormMapper.findByTrQueryOrder(selects, selectinput, currentPage, pagesize, null, null);
		} else {
			// 普通员工则先获取，自己正管理的客户
			// List<Integer> selectByUserid = customerMapper.selectByUserid(uid);

			// 存储此员工管理的所有的客户Id
			List<Integer> allids = new ArrayList<>();

			if (selectinput.length() > 0 && !selectinput.trim().equals("")) {

				selectinput = "%" + selectinput + "%";
			}
			PageHelper.startPage(currentPage, pagesize);
			return deportFormMapper.findByTrQueryOrder(selects, selectinput, currentPage, pagesize, allids, uid);

		}

	}
	
	/**
	 * 出库出库单
	 * @param id
	 */
	public void del(Integer id,Integer uid) {
		Date date = new Date();
		deportFormMapper.deletTru(id,uid,date);
		JSONObject findBytnumTotru = deportFormMapper.findBytnumTotru(id);
		// 插入一个流水记录
		// 生成最大编号
		Integer mid = null;
		Integer findmid = deportFormMapper.findMaxLifeId();
		System.out.println(findmid);
		if (findmid != null && findmid != 0) {
				mid = findmid;
		}
					String dd = MaxId.generateNewOrderID2(mid);
		deportFormMapper.addoutputLife(Integer.parseInt(dd), Integer.parseInt(3025+""), findBytnumTotru.getInteger("dgsnum")
				, findBytnumTotru.getInteger("tquantity"), date, uid, findBytnumTotru.getInteger("cus_id"), id);
		
		//修改库存数量
		deportFormMapper.updateDeport(findBytnumTotru.getInteger("dnum"), findBytnumTotru.getInteger("tquantity"));
	}

	/////////////////////////////////
	//////////////////////////// 入库流水表
	/**
	 * 带条件的查询出入库流水表里的出库信息
	 * 
	 * @param selects     条件头
	 * @param selectinput 输入的客户名
	 * @param selectend   （废除）
	 * @param currentPage 页码
	 * @param pagesize    页大小
	 * @param uid         用户id
	 * @return
	 */
	public List<JSONObject> selectInoutlifeByPagerSql(String selects, String selectinput, String selectend,
			int currentPage, int pagesize, int uid) {

		// 查询当前员工是老板还是普通员工
		String selectByBoss = userMDAO.selectByBoss(uid);
		if (selectByBoss != null && selectByBoss.length() > 0) {
			if (selectinput.length() > 0 && !selectinput.trim().equals("")) {

				selectinput = "%" + selectinput + "%";
			}
			PageHelper.startPage(currentPage, pagesize);
			return deportFormMapper.findByIOQueryOrder(selects, selectinput, currentPage, pagesize, null, null, 999);
		} else {
			// 普通员工则先获取，自己正管理的客户
			// List<Integer> selectByUserid = customerMapper.selectByUserid(uid);

			// 存储此员工管理的所有的客户Id
			List<Integer> allids = new ArrayList<>();

			if (selectinput.length() > 0 && !selectinput.trim().equals("")) {

				selectinput = "%" + selectinput + "%";
			}
			PageHelper.startPage(currentPage, pagesize);
			return deportFormMapper.findByIOQueryOrder(selects, selectinput, currentPage, pagesize, allids, uid, 999);

		}

	}

	/**
	 * 根据每条信息修改其出库和入库的对应信息
	 * 
	 * @param list
	 */
	public void updateInoutlifeByPagerSql(List<JSONObject> list) {
		// TODO Auto-generated method stub
		if (list != null && list.size() > 0) {
			for (JSONObject jsonObject : list) {
				//System.out.println(jsonObject);
				if (jsonObject.getInteger("nums") != null && jsonObject.getInteger("nums") != 0) {
					int nums = jsonObject.getInteger("nums");
					if (jsonObject.getInteger("oitype") == 3026) {
						// 入库
						// 如果是入库则需要在入库表查询供应商
						JSONObject findByinstocks = deportFormMapper.findByinstocks(nums);
						if (findByinstocks!=null) {
						jsonObject.put("oifillman", findByinstocks.getString("supname"));
						jsonObject.put("goo_name", findByinstocks.getString("goo_name"));
						jsonObject.put("goo_id", findByinstocks.getInteger("goo_id"));}
					} else if (jsonObject.getInteger("oitype") == 3025) {
						// 出库
						JSONObject findByinstocks = deportFormMapper.findBytreasury(nums);
						if (findByinstocks!=null) {
							jsonObject.put("oifillman", findByinstocks.getString("cus_name"));
							jsonObject.put("goo_name", findByinstocks.getString("goo_name"));
							jsonObject.put("goo_id", findByinstocks.getString("goo_id"));
						}
						
					}
				}

			}

		}

	}

	/**
	 * lsl生成入库单
	 * @param inst
	 */
	public void insert(Inst inst) {
		dao.save(inst);
	}
	/**
	 * lsl添加入库明细
	 * 
	 * @param id
	 * @param cart
	 */
	public void addinsDetail(Integer id, CartBoxpur cart) {
		// 查询订单概述对象
		// orderFormMapper.updateSumCount(cart.getPrice(), cart.getQuatitys(), id);
		List<Cartpur> map = cart.getMap();
		for (Cartpur cart2 : map) {

			Integer fll = null;
			Integer findMaxId = deportFormMapper.findMaxIdDetail();
			System.out.println(findMaxId);
			if (findMaxId != null && findMaxId != 0) {
				fll = findMaxId;
			}
			String detailid = MaxId.generateNewOrderID2(fll);
			deportFormMapper.insertintodetail(id, detailid, cart2.getGoods().getGooId(), cart2.getQuatity(),
					cart2.getGoods().getGooName(), cart2.getSum(), cart2.getDesc());
			// orderdetails.add(orderdetail);
		}
	}


}
